package org.sixtynine.stock.dao.impl;

/**
 * @author Thilan
 *
 */

import java.util.Calendar;
import java.util.Date;
import java.util.List;





import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.sixtynine.stock.Constants;
import org.sixtynine.stock.dao.IntradayShareDataDao;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.IntradayShareData;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class IntradayShareDataDaoImpl extends AbstractDaoImpl<IntradayShareData , Integer> implements
		IntradayShareDataDao {

	protected IntradayShareDataDaoImpl() {
		super(IntradayShareData.class);
	}

	@Override
	public void saveIntradayShareData(IntradayShareData intradayShareData) {
		saveOrUpdate(intradayShareData);
	}

	@Override
	public List<IntradayShareData> findIntradayShareData(int company) {
		return findByCriteria(Restrictions.eq("companyId", company));
	}

	@Override @Transactional
	public void deleteOldRecords() {
		
		Calendar today = Calendar.getInstance();
		today.set(Calendar.HOUR, 0);
		today.set(Calendar.MINUTE, 0);
		today.set(Calendar.SECOND, 0);
		
		Query query = getCurrentSession().createQuery("delete from IntradayShareData where time < :time " );
		query.setParameter("time", today.getTime());
		
		query.executeUpdate();
	}
	
	
	@Override
	public List<IntradayShareData> searchIntradayShareData(int companyId,
			Date fromDate, Date toDate) {
		Criteria criteria = getCurrentSession().createCriteria(
				IntradayShareData.class);

		if (companyId > Constants.ERROR) {
			criteria.add(Restrictions.eq("company.id", companyId));
		}
		if (fromDate != null) {
			criteria.add(Restrictions.ge("date", fromDate));
		}

		if (toDate != null) {
			criteria.add(Restrictions.le("date", toDate));
		}

		return findByCriteria(criteria);
	}

	@Override
	public Page<IntradayShareData> searchIntradayShareData(int companyId,
			Date fromDate, Date toDate, GridPramDTO gridPramDTO) {
		Criteria criteria = getCurrentSession().createCriteria(
				IntradayShareData.class);

		if (companyId > Constants.ERROR) {
			criteria.add(Restrictions.eq("company.id", companyId));
		}
		if (fromDate != null) {
			criteria.add(Restrictions.ge("date", fromDate));
		}

		if (toDate != null) {
			criteria.add(Restrictions.le("date", toDate));
		}

		return findByCriteria(criteria, gridPramDTO);
	}


}
